﻿using System;
using System. Collections. Generic;
using System. IO;
using System. Windows;
using System. Windows. Controls;
using System. Windows. Media. Imaging;
using System. Xml. Linq;
using Microsoft. Phone. Tasks;
using WP7_WebLib. HttpPost;
using 测试_osmobile_API. Config;
using 测试_osmobile_API. Model;

namespace 测试_osmobile_API.API_Test
{
    public partial class Post_Pub : UserControl
    {
        public Post_Pub()
        {
            InitializeComponent();
        }

        private void btn_Post_Pub_Click(object sender, RoutedEventArgs e)
        {
//            catalog	整数	文章存放的分类，允许选择多个分类
//title	字符串	文章标题
//body	字符串	文章完整内容
//tag	字符串	文章的标签，使用逗号或者空格隔开的字符串
//img	二进制	上传的图片，可能包含多个 img 参数
            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                {"catalog", txt_catalog.Text.Trim()},
                {"title", txt_title.Text.Trim()},
                {"body", txt_body.Text.Trim()},
                {"tag", txt_tags.Text.Trim()},
                //等下用 Picture选择器 来解决
                //{"img", txt_Body.Text},
            };
            PostClient client = new PostClient(parameters);
            client.DownloadStringCompleted += (s, e1) =>
            {
                if (e1.Error != null)
                {
                    System.Diagnostics.Debug.WriteLine("添加文章失败: {0}", e1.Error.Message);
                    return;
                }
                XElement x = XElement.Parse(e1.Result).Element("result");
                error _error = new error
                {
                    errorCode = x.Element("errorCode").Value.ToInt32(),
                    errorMessage = x.Element("errorMessage").Value,
                };
                //分析错误代码
                System.Diagnostics.Debug.WriteLine(_error);
                MessageBox.Show(_error.errorMessage, _error.errorCode.ToString(), MessageBoxButton.OK);
            };
            client. DownloadStringAsync(new Uri(AppConfig. Instance. GetApi("osmobile=post&action=pub"), UriKind. Absolute), CookieUtil. Instance. Cookie_All);
        }

        private PhotoChooserTask photoChooser;
        private BitmapImage bmpSource;
        //选择图片
        private void btn_ChosePic_Click(object sender, RoutedEventArgs e)
        {
            //PhotoChooserTask photoChooser = new PhotoChooserTask( );
            this. photoChooser = new PhotoChooserTask( );
            this. photoChooser. Completed += new EventHandler<PhotoResult>(photoChooser_Completed);
            //不需要裁剪相片
            this. photoChooser. ShowCamera = true;
            this. photoChooser. Show( );
        }

        private void photoChooser_Completed(object sender, PhotoResult e)
        {
            if ( e. TaskResult == TaskResult. OK )
            {
                this. bmpSource = new BitmapImage( );
                bmpSource. SetSource(e. ChosenPhoto);
                this. lbl_ChosePic. Text = e. OriginalFileName;
                //现在讲 bmpSource 转换成 byte[]
            }
            else
            {
                this. lbl_ChosePic. Text = string. Empty;
            }
        }

        private byte[ ] ConvertPhotoToByteArray( )
        {
            if ( this.bmpSource == null )
            {
                return null;
            }
            byte[] data;
            // Get an Image Stream
            using (MemoryStream ms = new MemoryStream())
            {

                WriteableBitmap btmMap = new WriteableBitmap(this. bmpSource);
                
                //write an image into the stream
                //Extensions.SaveJpeg(btmMap, ms,
                //bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);

                // reset the stream pointer to the beginning
                ms.Seek(0, 0);
                //read the stream into a byte array
                data = new byte[ms.Length];
                ms.Read(data, 0, data.Length);
            }
            //data now holds the bytes of the image
            return data;
        }

    }
}
